import axios from "axios"
import { getToken, removeToken } from './tools'

const instance = axios.create({
  baseURL: "/",
  timeout: 5000
})

instance.interceptors.request.use((config) => {
  // Nprogress.start();
  // 判断是否存在token，如果存在的话，则每个http header都加上token
  // 除了login页面
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  // Nprogress.remove();
  // notification.error({
  //   description: '您的网络发生异常，无法连接服务器',
  //   message: '请求超时',
  // });
  return Promise.reject(error);
});

instance.interceptors.response.use(
  (response) => {
    // Nprogress.done();
    const { data, status } = response;
    if (status !== 200) {// 401
      // notification.error({
      //   message: "错误",
      //   description: "权限验证失败",
      // });
      removeToken()
      return Promise.reject(status)
    }
    if (data.ret !== 1) {
      // notification.error({
      //   message: "错误",
      //   description: data.msg || "未知错误",
      // });
      return Promise.reject(data)
    }
    return response.data;
  },
  (err) => {
    // Nprogress.done();
    if (err.message === "cancel") {
      console.log("abort()")
    } else {
      // notification.error({
      //   description: '您的网络发生异常，无法连接服务器',
      //   message: '请求超时',
      // });
    }
    return Promise.reject(err);
  }
);

export const CancelToken = axios.CancelToken;

/*
useEffect(() => {
  var CancelToken = axios.CancelToken;
  var source1 = CancelToken.source();
  var source2 = CancelToken.source();
  getPipeQuery({
    action: "1",
  }, source1.token).then(res1 => {
    if (res1.data.ret === 1) {
      setPipe(res1.data.data)

      getWellQuery({ action: "1" }, source2.token).then(res2 => {
        if (res2.data.ret === 1) {
          setWelle(res2.data.data)
        }
      }).catch(err1 => {
        console.log(err1)
      })
    }
  }).catch(err2 => {
    console.log(err2)
  })
  return () => {
    // cleanup
    source1.cancel("cancel")
    source2.cancel("cancel")
  }
}, [layerLoading])
*/

export default instance;

